package controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import service.ContractModelServiceImp;
import service.ContractTypeServiceImp;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.naming.NamingEnumeration;
import javax.servlet.http.HttpServletRequest;

import domain.ContractModel;
import domain.ContractType;
import domain.Return;
import utils.FileUtil;
import utils.GsonUtils;

/**
 * User: xinxin
 * Date: 2016-10-27
 * Time: 22:30
 * FIXME
 */
@Controller
@RequestMapping("/specific_lawyer_back")
public class SpecificLawyerBackController {
    private static final Logger LOG = LoggerFactory.getLogger(SpecificLawyerBackController.class);
    @Autowired
    ContractModelServiceImp mContractModelServiceImp;
    @Autowired
    ContractTypeServiceImp mContractTypeServiceImp;
    @Autowired
    SpecificLawyerController mSpecificLawyerController;


    @RequestMapping("/json_contract_all/{pageIndex}")
    @ResponseBody
    public Return jsonContractShowAll(@PathVariable("pageIndex") int pageIndex) {
        return mSpecificLawyerController.jsonContractShowAll(pageIndex);
    }

    @RequestMapping("/json_contract/{contractId}")
    @ResponseBody
    public Return jsonContractShowOne(@PathVariable("contractId") int contractId) {
        return mSpecificLawyerController.jsonContractShowOne(contractId);
    }


    /**
     * 通过typeid去查找合同范本
     * 至少需要将typeId和pageIndex传入，否则会出错
     *
     * @param typeId
     * @param pageIndex
     * @param perPage
     * @return
     */
    @RequestMapping("/json_contract_query_typeId")
    @ResponseBody
    public Return jsonContractQueryAllByTypeId(@RequestParam("typeId") int typeId, @RequestParam(value = "pageIndex") int pageIndex, @RequestParam(value = "perPage", required = false, defaultValue = "10") int perPage) {
        List<ContractModel> contractModels = mContractModelServiceImp.selectModelByTypeId(typeId, pageIndex, perPage);
        for (ContractModel contractModel : contractModels) {
            System.out.println(contractModel);
        }
        if (contractModels.size() > 0) {
            return Return.commonReturn().setData(contractModels);
        }
        return Return.faliReturn().setMesg("未获取到内容");
    }

    /**
     * 至少需要将name和pageIndex传入，否则会出错
     *
     * @param name
     * @param pageIndex
     * @param perPage
     * @return
     */
    @RequestMapping("/json_contract_query_name")
    @ResponseBody
    public Return jsonContractQueryAllByName(@RequestParam("name") String name, @RequestParam(value = "pageIndex") int pageIndex, @RequestParam(value = "perPage", required = false, defaultValue = "10") int perPage) {
        if (name.equals("")) {
            return Return.faliReturn().setMesg("请输入查询内容");
        }
        List<ContractModel> contractModels = mContractModelServiceImp.selectModelByName(name, pageIndex, perPage);
        if (contractModels.size() > 0) {
            return Return.commonReturn().setPageNum(pageIndex).setData(contractModels);
        } else {
            return Return.faliReturn().setMesg("没有查询到" + name + "的内容");
        }
    }

    /**
     * 根据id去查询合同的详细描述
     *
     * @param contractId
     * @return
     */
    @RequestMapping("/json_contract_query_id/{contractId}")
    @ResponseBody
    public Return jsonContractQueryById(@PathVariable("contractId") int contractId) {
        ContractModel contractModel = mContractModelServiceImp.selectModelById(contractId);
        if (contractModel != null) {
            return Return.commonReturn().setData(contractModel);
        } else {
            return Return.faliReturn().setMesg("未查询到对应id的合同");
        }
    }

    //我们在UserController这个控制器里添加这个方法
    @RequestMapping(value = "/uploadContrctFile"
            , method = RequestMethod.POST
            , produces = "application/json; charset=utf-8")
    @ResponseBody//参数名file必须和html中的name属性相对应
    public Return uploadContractFile(@RequestParam(value = "contractId", required = false, defaultValue = Integer.MAX_VALUE + "") int contractId, @RequestParam(required = false) MultipartFile file, HttpServletRequest request) {
        //在这里面文件存储的方案一般是：收到文件→获取文件名→在本地存储目录建立防重名文件→写入文件→返回成功信息
        //如果上面的步骤中在结束前任意一步失败，那就直接失败了。
        System.out.println(file);
        if (null == file || file.isEmpty()) {
            return Return.faliReturn().setMesg("文件不能为空");
        }
        //设置文件保存的本地路径
        String filePath = request.getSession().getServletContext().getRealPath("/uploadFiles/");
        String fileName = file.getOriginalFilename();
        String fileType = fileName.split("[.]")[1];
        //为了避免文件名重复，在文件名前加UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String uuidFileName = uuid + fileName;
//        File f = new File(filePath + "/" + uuid + "." + fileType);
        //将文件保存到服务器
        File targetFile = new File(filePath, uuidFileName);
        //保存
//        try {
//            file.transferTo(targetFile);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        try {
            FileUtil.upFile(file.getInputStream(), uuidFileName, filePath);
            //这里直接对文件的地址进行修改
            if (contractId != Integer.MAX_VALUE) {
                final ContractModel contractModel = mContractModelServiceImp.selectModelById(contractId);
                contractModel.setLocation(targetFile.getAbsolutePath());
                mContractModelServiceImp.updateModel(contractModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Return.commonReturn().setMesg("上传文件成功").setData(targetFile);
    }


    @RequestMapping(value = "/json_contract_delete", method = RequestMethod.POST)
    @ResponseBody
    public Return jsonContractDeleteOne(@RequestParam(value = "contrct_id") Integer contractId) {
        if (mContractModelServiceImp.deleteModel(contractId)) {
            return Return.successReturn();
        }
        return Return.faliReturn().setMesg("删除"+contractId+"失败，请稍后再试");
    }

    @RequestMapping(value = "/json_contract_add", method = RequestMethod.POST)
    @ResponseBody
    public Return jsonContractAddContract(@RequestBody ContractModel contractModel) {
        System.out.println(contractModel);
        if (mContractModelServiceImp.newModel(contractModel)) {
            return Return.successReturn();
        }
        return Return.faliReturn().setMesg("新增合同失败");
    }

    /**
     * 直接接收一个json对象来进行更改操作
     *
     * @param contractModel
     * @return
     */
    @RequestMapping(value = "/json_contract_change", method = RequestMethod.POST)
//@ModelAttribute("contract_model")
    @ResponseBody
    public Return jsonContractChangeContract(@RequestBody ContractModel contractModel) {
        System.out.println(contractModel);
        if (mContractModelServiceImp.updateModel(contractModel)) {
            return Return.successReturn();
        }
        return Return.faliReturn();
    }
//    /**
//     * 接收request来处理数据
//     * @param
//     * @return
//     */
//    @RequestMapping(value = "/json_contract_change/", method = RequestMethod.POST)
//    @ResponseBody
//    public Return jsonContractChangeContract(HttpServletRequest request, HttpServletResponse response) {
////        if (mContractModelServiceImp.updateModel(contractModel)) {
////            return Return.successReturn();
////        }
//        return Return.faliReturn();
//    }

    @RequestMapping("/json_contract_type_all/{pageIndex}")
    @ResponseBody
    public List<ContractType> jsonContractTypeAll(@PathVariable("pageIndex") int pageIndex) {
        List<ContractType> contractTypes = mContractTypeServiceImp.selectModelTypeAll(pageIndex);
        for (ContractType contractType : contractTypes) {
            System.out.println(contractType);
        }
        return contractTypes;
    }
}
